﻿namespace DataDuctus.MongoDb.Serialization.Extensions
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Reflection;
	using System.Runtime.Serialization;

	internal static class TypeExtensions
	{
		internal static bool IsInInheritanceChain(this Type typeToCheck, Type typeToExpand)
		{
			for (Type t = typeToCheck; t != null; t = t.BaseType)
			{
				if (t.Equals(typeToExpand))
				{
					return true;
				}
			}

			for (Type t = typeToExpand; t != null; t = t.BaseType)
			{
				if (t.Equals(typeToCheck))
				{
					return true;
				}
			}

			return false;
		}

		internal static IEnumerable<Type> GetDataContractInheritanceChain(this Type type)
		{
			var list = new List<Type>();

			for(Type t = type;t != null;t = t.BaseType)
			{
				if (null == t.GetAttribute<DataContractAttribute>())
				{
					break;
				}

				list.Add(t);
			}

			list.Reverse();
			
			return list;
		}

		public static IEnumerable<PropertyInfo> ToSerializableProperties(this Type type)
		{
			return from pinfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
			       where pinfo.HasAttribute<DataMemberAttribute>()
			       select pinfo;
		}

		public static IEnumerable<FieldInfo> ToSerializableFields(this Type type)
		{
			return
				from field in
					type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
				where field.HasAttribute<DataMemberAttribute>()
				select field;
		}
	}
}
